package com.zhangxi.websqlit.user.service.impl;

import com.zhangxi.websqlit.common.entity.MailEntity;
import com.zhangxi.websqlit.common.util.DataUtil;
import com.zhangxi.websqlit.common.util.FileImageUtil;
import com.zhangxi.websqlit.common.util.MailUtil;
import com.zhangxi.websqlit.contact.repository.ContactDao;
import com.zhangxi.websqlit.file.service.FileInfoService;
import com.zhangxi.websqlit.mybatis.entity.PtContactEnity;
import com.zhangxi.websqlit.mybatis.entity.PtFileEntity;
import com.zhangxi.websqlit.mybatis.entity.PtUserEntity;
import com.zhangxi.websqlit.user.entity.MailVfcCodeEntity;
import com.zhangxi.websqlit.user.entity.UserSearchEntity;
import com.zhangxi.websqlit.user.exception.MoreMailException;
import com.zhangxi.websqlit.user.exception.NotMailException;
import com.zhangxi.websqlit.user.repository.UserInfoDao;
import com.zhangxi.websqlit.user.service.UserInfoService;

import org.apache.commons.mail.EmailException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;
import java.util.Locale;

@Service
public class UserInfoServiceImpl implements UserInfoService {
    private final static String HEAD_PHOTO_ID = "10001";
    @Resource
    private UserInfoDao userInfoDao;
    @Resource
    private FileInfoService fileInfoService;
    @Value("${passwd.key}")
    private String passwdKey;
    @Value("${mail.host.name}")
    private String mailHostName;
    @Value("${mail.from.user}")
    private String mailFromUser;
    @Value("${mail.from.pwd}")
    private String mailFromPwd;
    @Resource
    private ContactDao contactDao;

    @Resource
    protected MessageSource messageSource;

    @Override
    public List<PtUserEntity> queryUserList(UserSearchEntity search) {
        org.springframework.util.DigestUtils aa;
        return userInfoDao.queryUserList(search);
    }

    @Override
    public PtUserEntity queryLogin(String userName, String password) {
        password = DigestUtils.md5DigestAsHex((password + passwdKey).getBytes());
        PtUserEntity entity = userInfoDao.queryLogin(userName,password);
        return entity;
    }

    @Override
    public PtUserEntity queryUserInfoById(String userUuid) {
        return userInfoDao.queryUserInfoById(userUuid);
    }

    @Override
    public Integer updateUserInfoById(PtUserEntity entity) {
        Integer count = 0;
        count = userInfoDao.queryUserInfoByItem(entity);
        if(count > 0){
            return count;
        }
        userInfoDao.updateUserInfoById(entity);
        return count;
    }

    @Override
    public void updateUserPasswdById(PtUserEntity entity) {
        String password = DigestUtils.md5DigestAsHex((entity.getPassword() + passwdKey).getBytes());
        entity.setPassword(password);
        userInfoDao.updateUserPasswdById(entity);
    }

    @Override
    public void regiterUser(PtUserEntity entity) {
        String password = DigestUtils.md5DigestAsHex((entity.getPassword() + passwdKey).getBytes());
        entity.setPassword(password);
        entity.setUserUuid(DataUtil.getUUID());
        userInfoDao.regiterUser(entity);
    }

    @Override
    public Integer queryUserInfoCount(PtUserEntity entity) {
        return userInfoDao.queryUserInfoByItem(entity);
    }

    @Override
    public String unloadPhoto(String fileName, InputStream inputStream, String userUuid) {

        String fileUuid = "";
        PtUserEntity userEntity = userInfoDao.queryUserInfoById(userUuid);
        if(userEntity == null){
            return fileUuid;
        }
        InputStream inputStreamZip = FileImageUtil.scaleImage(inputStream,40,"jpg");
        String folderUuid=userEntity.getFolderId();
        if(folderUuid == null){
            PtFileEntity fileEntity = new PtFileEntity();
            fileEntity.setParentUuid(HEAD_PHOTO_ID);
            fileEntity.setFileName(userEntity.getUserName());
            folderUuid = fileInfoService.mkdir(fileEntity);
        }
        fileUuid = fileInfoService.uploadFile(fileName,inputStreamZip,folderUuid);
        userEntity.setFolderId(folderUuid);
        userEntity.setHeadPhotoId(fileUuid);
        userInfoDao.updateUserPhoto(userEntity);
        return fileUuid;
    }

    @Override
    public List<PtContactEnity> queryFriendsListById(String userUuid, String searchUserKey) {
        List<PtContactEnity> ptContactEnityList = userInfoDao.queryFriendsListById(userUuid, searchUserKey);
        List<PtContactEnity> ptContactEnityListExit = contactDao.queryContactListById(new UserSearchEntity(userUuid));
        for(PtContactEnity item:ptContactEnityList){
            for(PtContactEnity itemExit:ptContactEnityListExit){
                if(item.getContactUuid().equals(itemExit.getContactUuid())){
                    item.setIsFriends(1);
                    break;
                }
            }
        }
        return ptContactEnityList;
    }

    @Override
    public String getMailVfcCode(String email) throws NotMailException, MoreMailException {

        List<PtUserEntity> list = userInfoDao.queryUserInfoByMail(email);
        if(list == null || list.size() == 0){
            throw  new NotMailException("not mail");
        }else if(list.size() > 1){
            throw new MoreMailException("more mail:" + list.size());
        }

        Locale locale = LocaleContextHolder.getLocale();
        String mailSubject =  messageSource.getMessage("mail.verification.subject",null,locale);
        String verificationCode = DataUtil.getVfcCode(6);
        String mailContent = messageSource.getMessage("mail.verification.content",new String[]{verificationCode},locale);
        MailEntity mailEntity = new MailEntity();
        mailEntity.setMailHostName(mailHostName);
        mailEntity.setMailFromUser(mailFromUser);
        mailEntity.setMailFromPwd(mailFromPwd);
        mailEntity.setMaiToUser(email);
        mailEntity.setMailSubject(mailSubject);
        mailEntity.setMailContent(mailContent);
        String rst="";
        try {
            MailUtil.sendMail(mailEntity);
            rst = verificationCode;

        } catch (EmailException e) {
            e.printStackTrace();
        }
        return rst;
    }

    @Override
    public void updatePasswordByMail(MailVfcCodeEntity entity) throws NotMailException, MoreMailException {
        List<PtUserEntity> list = userInfoDao.queryUserInfoByMail(entity.getEmail());
        if(list == null || list.size() == 0){
            throw  new NotMailException("not mail");
        }else if(list.size() > 1){
            throw new MoreMailException("more mail:" + list.size());
        }
        String password = DigestUtils.md5DigestAsHex((entity.getPassword() + passwdKey).getBytes());
        entity.setPassword(password);
        userInfoDao.updatePasswordByMail(entity);
    }
}
